import React from 'react'
import styles from '@/assets/css/confirm.module.css';

const RoomConfirm = () => {
    const [searchParams] = React.Router.useSearchParams();
    const roomid =  searchParams.get('roomid') ? searchParams.get('roomid') : 0;
    const [dateshow, SetDateshow] = React.useState(false)
    const [guestshow, SetGuestshow] = React.useState(false)
    const [couponshow, SetCouponshow] = React.useState(false)
    const [payshow, SetPayshow] = React.useState(false)
    const [guestlist, SetGuestlist] = React.useState([])
    const [couponlist, SetCouponlist] = React.useState<any>([])
    //支付信息
    const [paylist] = React.useState([[
        { label: '余额支付', value: 'money' },
        { label: '微信支付', value: 'wx' },
        { label: '支付宝支付', value: 'zfb' },
    ]])
    // 价格
    const [price, SetPrice] = React.useState(0)
    // 原价
    const [originprice, SetOriginprice] = React.useState(0)
    // 天数
    const [day, SetDay] = React.useState(0);
    //房间信息
    const [RoomDetail, SetRoomDetail] = React.useState<any>({flag_text: [], price: 0})
    // 日期组件默认日期
    const defaultDateRange: [Date, Date] = [
        new Date(),
        new Date(new Date().getTime() + 86400000),
    ]

    //订单信息
    const [order, SetOrder] = React.useState({
        remark: '',
        //价格信息
        origin_price: 0,
        price: 0,
        //优惠券
        couponid: '',
        couponstr: '',
        //日期
        datestr: '',
        starttime: 0,
        endtime: 0,
        //住客
        guest: '',
        gueststr: '请选择住客信息',
        guestids: [],
        //支付方式
        paystr: '余额支付',
        pay: 'money'
    })

    // 初始化默认时间
    const getCurrentDate = (): void => 
    {
        // `2024-03-20 - 2024-03-25`
        var datestr = `${new Date(defaultDateRange[0]).toLocaleDateString()} - ${new Date(defaultDateRange[1]).toLocaleDateString()}`

        //标准时间转换为时间戳
        var starttime = Date.parse(new Date(defaultDateRange[0]).toLocaleDateString()) / 1000
        var endtime = Date.parse(new Date(defaultDateRange[1]).toLocaleDateString()) / 1000

        SetOrder({
            ...order,
            starttime,
            endtime,
            datestr
        })
    }

    React.useEffect(() => 
    {
        GetRoomInfoData();;
        GetGuestData();
        GetCouponData();
        getCurrentDate();
    }, [roomid])

    //当订单信息有变化，就重新计算价格
    React.useEffect(() => 
    {
        Total()
    }, [order, RoomDetail])

    // 酒店详情
    const GetRoomInfoData = async () => 
    {
        let result = await React.HTTP.post('/room/RoomInfo', {
            roomid: roomid
        })

        if (result && result.code == 1) 
        {
            SetRoomDetail(result.data.info);
        }
    }

    // 住客信息
    const GetGuestData = async() =>
    {
        let result = await React.HTTP.post('/room/GuestList', {
            busid: React.Business.id,
        })

        if(result.code === 1)
        {
            SetGuestlist(result.data);
        }
    }
    
    // 优惠券列表
    const GetCouponData = async() =>
    {
        let result = await React.HTTP.post('/room/CouponList', {
            busid: React.Business.id,
        })

        if(result.code === 1)
        {
            let data:any = [];
            result.data.map((item:any) =>{
                data.push({
                    label: `${item.coupon.title}-${item.coupon.rate*10}折`,
                    value: item.id,
                    rate: item.coupon.rate
                })
            })
            //给二维数组结构
            SetCouponlist([data]);
        }
    }
    
    //计算价格
    const Total = () => 
    {
        var starttime = order.starttime
        var endtime = order.endtime

        //时间差
        var durationSeconds = endtime - starttime;
        var day: any = Math.floor(durationSeconds / 86400);

        //原价 时间差*房间原价
        var truncateToTwoDecimals = (num: number) => Math.trunc(num * 100) / 100;
        const origin_price:any = truncateToTwoDecimals(day * parseFloat(RoomDetail.price));
        var price:any = origin_price

        //是否有选择优惠券
        if (order.couponid && couponlist[0]?.length) 
        {
            var coupon = couponlist[0].find((item: any) => item.value === order.couponid);
            if (coupon) 
            {
                price = truncateToTwoDecimals(price * coupon.rate);
            }
        }

        //修改价格
        SetPrice(price)
        SetOriginprice(origin_price)
        SetDay(day)
    }

    // 日期选择
    const DateConfirm = (val: any) => 
    {
        SetDateshow(false)

        // `2024-03-20 - 2024-03-25`
        var datestr = `${new Date(val[0]).toLocaleDateString()} - ${new Date(val[1]).toLocaleDateString()}`

        //获取到开始时间和结束时间
        //标准时间转换为时间戳
        var starttime = Date.parse(new Date(val[0]).toLocaleDateString()) / 1000
        var endtime = Date.parse(new Date(val[1]).toLocaleDateString()) / 1000

        SetOrder({
            ...order,
            starttime,
            endtime,
            datestr
        })
    }

    // 住客选择
    const GuestChange = async (value: string[]) => 
    {
        var gueststr: any = []
        var guestids: any = []

        //循环遍历
        guestlist.map((item: any) => {
            if (value.includes(item.id)) 
            {
                gueststr.push(item.nickname)
                guestids.push(item.id)
            }
        })

        var str = gueststr.join('、')
        var ids = guestids.join(',')

        //设置订单数据
        SetOrder({
            ...order,
            gueststr: str,
            guest: ids,
            guestids
        })
    }

    // 优惠券选择
    const CouponChange = async (value: any) => 
    {

        SetCouponshow(false)

        var couponstr = ''

        if(couponlist.length <= 0)
        {
           React.error('暂无优惠券')
           return false;
        }


        //获取picker第一项
        var list: any = couponlist[0]

        list.map((item: any) => {
            if (item.value == value[0]) 
            {
                couponstr = item.label
            }
        })

        SetOrder({
            ...order,
            couponstr,
            couponid: value[0],
        })
    }

    // 订单备注
    const RemarkChange = (e:any) =>
    {
        SetOrder({
            ...order,
            remark:e
        })
    }

    // 支付方式
    const PayChange = async (value: any) => 
    {

        SetPayshow(false)

        var paystr = ''

        //获取picker第一项
        var list: any = paylist[0]

        list.map((item: any) => {
            if (item.value == value[0]) 
            {
                paystr = item.label
            }
        })

        SetOrder({
            ...order,
            paystr,
            pay: value[0],
        })
    }

    const ConfirmOrder = async () => 
    {

        if(day <= 0)
        {
            return React.error('请选择入住日期')
        }

        if(order.guestids.length <= 0)
        {
            return React.error('请选择住客')
        }

        let data = {
            busid: React.Business.id,
            roomid: roomid,
            guest: order.guest,
            starttime: order.starttime,
            endtime: order.endtime,
            couponid: order.couponid ?? '',
            remark: order.remark,
            pay: order.pay
        }

        // 余额支付
        if(order.pay == 'money')
        {
            let result = await React.HTTP.post('/room/OrderAdd', data)
            if (result.code == 1) 
            {
                React.success(result.msg, () => React.navigate(result.url))
            }
            else 
            {
                React.error(result.msg)
            }
        } 
        else 
        {
            let result = await React.HTTP.post('/room/OrderAdd', data)
            if (result.code == 1) 
            {
                React.success(result.msg, () => React.navigate(`/room/pay?payid=${result.data.id}`))
            }
            else 
            {
                React.error(result.msg)
            }
        }

    }


    return (
        <>
            <div className={styles.skeleton}>
                <div className={styles.detail}>
                    <div className={styles.thumb}>
                        <img src={RoomDetail.thumb_text} alt="" />
                    </div>
                    <div className={styles.right}>
                        <p>{RoomDetail.name}</p>
                        <p>￥{RoomDetail.price} / 晚</p>
                        <div className={styles.tips}>
                            {RoomDetail.flag_text && RoomDetail.flag_text.map((flag: any, index: any) => <span key={index}> {flag} </span>)}
                        </div>
                    </div>
                </div>

                <div className={styles.skeleton_rect}>
                    {/* 入住日期 */}
                    <div className={styles.item}>
                        <label>入住日期</label>
                        <React.UI.Input type="text" className={styles.item_right} placeholder="请选择入住日期"
                            value={order.datestr} onClick={() => SetDateshow(true)} />
                    </div>
                    {/* 日期选择 */}
                    <React.UI.CalendarPicker
                        visible={dateshow}
                        min={new Date()}
                        defaultValue={defaultDateRange}
                        selectionMode='range'
                        onClose={() => SetDateshow(false)}
                        onMaskClick={() => SetDateshow(false)}
                        onConfirm={DateConfirm}
                    >
                    </React.UI.CalendarPicker>


                    {/* 住客信息 */}
                    <div className={styles.item}>
                        <label>住客信息</label>
                        <div className={order.guestids.length > 0 ? styles.item_right : styles.item_rights} onClick={() => SetGuestshow(true)}>
                            {order.gueststr}
                        </div>

                        {/* 弹出层组件 */}
                        <React.UI.Popup
                            visible={guestshow}
                            onMaskClick={() => SetGuestshow(false)}
                            destroyOnClose
                        >
                            <div
                                style={{ height: '40vh', overflowY: 'scroll', padding: '20px' }}
                            >
                                <React.UI.CheckList
                                    multiple={true}
                                    defaultValue={order.guestids}
                                    onChange={GuestChange}
                                >
                                    {guestlist && guestlist.map((item: any, key: number) =>
                                        <React.UI.CheckList.Item key={key} value={item.id}>
                                            {item.nickname}
                                        </React.UI.CheckList.Item>
                                    )}
                                </React.UI.CheckList>

                                <React.UI.Button color="primary" block style={{ width: '100%' }} onClick={() => SetGuestshow(false)}>确认</React.UI.Button>

                            </div>
                        </React.UI.Popup>
                    </div>
                </div>

                {/* 优惠券 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>优惠券</div>
                    <p>{order.couponstr}</p>
                    <React.UI.Button size="mini" color="primary" onClick={() => SetCouponshow(true)}>选择</React.UI.Button>

                    {/* 弹框选项 */}
                    <React.UI.Picker
                        columns={couponlist}
                        visible={couponshow}
                        onClose={() => SetCouponshow(false)}
                        onConfirm={CouponChange}
                    >
                    </React.UI.Picker>
                </div>

                {/* 支付方式 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>支付方式</div>
                    <p>{order.paystr}</p>
                    <React.UI.Button size="mini" color="primary" onClick={() => SetPayshow(true)}>选择</React.UI.Button>

                    <React.UI.Picker
                        columns={paylist}
                        visible={payshow}
                        onClose={() => SetPayshow(false)}
                        onConfirm={PayChange}
                    >
                    </React.UI.Picker>
                </div>

                {/* 订单备注 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>订单备注</div>
                    <React.UI.TextArea
                       defaultValue={'请输入订单备注'} value={order.remark} showCount maxLength={120} onChange={RemarkChange}
                    />
                </div>

                {/* 费用 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>房间费用</div>
                    <div className={styles.prices}>
                        <span>￥{originprice}</span>
                        <span>共 {day} 晚</span>
                    </div>
                </div>
            </div>

            <div className={styles.comfirm_foot_bar}>
                {price == originprice ?
                    <div className={styles.text}>
                        <span>总价:</span>
                        <span>￥{price}</span>
                    </div> :
                    <div className={styles.text}>
                        <span>优惠价格:</span>
                        <span>￥{price}</span>
                        <s>原价：￥{originprice}</s>
                    </div>
                }
                <React.UI.Button onClick={ConfirmOrder} color='primary' shape='rounded'>提交订单</React.UI.Button>
            </div>
        </>
    )
}

export default RoomConfirm;